<!-- components/ImageSelector.vue -->
<template>
  <div class="image-selector">
    <div class="image-selector__header">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索图片..."
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
      />
      <el-button
          type="danger"
          :disabled="!selectedImages.length"
          @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>
        删除选中 ({{ selectedImages.length }})
      </el-button>
    </div>

    <div v-loading="loading" class="image-selector__content">
      <div v-if="imageList.length" class="image-grid">
        <div
            v-for="image in imageList"
            :key="image.id"
            class="image-item"
        >
          <el-checkbox
              v-model="selectedImages"
              :label="image.id"
              @change="handleSelect"
          />
          <el-image
              :src="image.url"
              fit="cover"
              class="image-preview"
              :preview-teleported="true"
              :initial-index="imageList.indexOf(image)"
              :preview-src-list="imageList.map(img => img.url)"
          >
            <template #placeholder>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <div class="image-info">
            <el-tooltip :content="image.originalName" placement="top">
              <span class="image-name">{{ image.originalName }}</span>
            </el-tooltip>
            <span class="image-date">{{ formatDate(image.createTime) }}</span>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂无图片" />
    </div>

    <div class="image-selector__footer">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Picture, Search } from '@element-plus/icons-vue'
import { getImageList, batchDeleteImages } from '@/api/image'
import { formatDate } from '@/utils/date'

const emit = defineEmits(['select'])

// 数据状态
const loading = ref(false)
const imageList = ref([])
const selectedImages = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)
const searchKeyword = ref('')

// 获取图片列表
const fetchImages = async () => {
  loading.value = true
  try {
    const res = await getImageList({
      page: currentPage.value - 1,  // 根据后端分页习惯调整
      size: pageSize.value,
      keyword: searchKeyword.value
    })
    if (res.data && res.data.records) {
      imageList.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取图片列表失败:', error)
    ElMessage.error('获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 增加获取选中图片信息的方法
const getSelectedImages = () => {
  return imageList.value.filter(image => selectedImages.value.includes(image.id))
}

// 选中图片处理
const handleSelect = () => {
  emit('select', selectedImages.value)
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchImages()
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedImages.value.length) return

  try {
    await ElMessageBox.confirm('确定要删除选中的图片吗？', '警告', {
      type: 'warning'
    })

    await batchDeleteImages(selectedImages.value)
    ElMessage.success('删除成功')
    selectedImages.value = []
    await fetchImages()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchImages()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchImages()
}

// 暴露方法给父组件
defineExpose({
  getSelected: () => selectedImages.value,
  getSelectedImages,
  clearSelection: () => {
    selectedImages.value = []
  }
})

onMounted(() => {
  fetchImages()
})
</script>

<style scoped>
/* 添加以下样式来优化预览效果 */
:deep(.el-image-viewer__wrapper) {
  z-index: 2100; /* 确保预览窗口在最上层 */
}

:deep(.el-image-viewer__img) {
  user-select: none; /* 防止图片被选中 */
}

/* 优化图片加载过渡效果 */
.image-preview {
  transition: opacity 0.3s ease;
}

.image-preview.is-loading {
  opacity: 0.6;
}

.image-selector {
  padding: 20px;
}

.image-selector__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.image-selector__header .el-input {
  width: 300px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.image-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.image-item:hover {
  transform: translateY(-2px);
}

.image-item .el-checkbox {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 2;
}

.image-preview {
  width: 100%;
  height: 200px;
  display: block;
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: #f5f7fa;
  font-size: 24px;
  color: #909399;
}

.image-info {
  padding: 8px;
}

.image-name {
  display: block;
  font-size: 14px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-date {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.image-selector__footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-empty {
  padding: 40px 0;
}
</style>